<template>
    <!-- 待配包确认 -->
    <div class="company-user-list">
        <!-- <ul class="global-operation-list">
            <li class="global-operation-left">
                <ul class="global-filter-list">
                    <li class="global-filter-item">
                        <h2 class="global-filter-item-title">关键字：</h2>
                        <el-input v-model="searchForm.keyword" autocomplete="off"></el-input>
                    </li>
                    <li class="global-filter-item">
                        <h2 class="global-filter-item-title">文件类型：</h2>
                        <el-select v-model="searchForm.fileType" clearable filterable>
                            <el-option v-for="(item, index) in fileTypeList" :key="index" :label="item.sysValueName"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </li>
                    <li class="global-filter-item">
                        <h2 class="global-filter-item-title">驳回状态：</h2>
                        <el-select v-model="searchForm.rejectStatus" clearable filterable>
                            <el-option v-for="(item, index) in rejectStatusList" :key="index" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                    </li>
                    <li class="global-filter-item">
                        <h2 class="global-filter-item-title">创建时间：</h2>
                        <el-date-picker v-model="searchForm.createDate" type="daterange" align="right" unlink-panels
                            range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                            :picker-options="pickerOptions">
                        </el-date-picker>
                    </li>
                    <li class="global-filter-item">
                        <h2 class="global-filter-item-title">驳回时间：</h2>
                        <el-date-picker v-model="searchForm.rejectDate" type="daterange" align="right" unlink-panels
                            range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
                            :picker-options="pickerOptions">
                        </el-date-picker>
                    </li>
                    <li class="global-filter-item">
                        <el-button type="primary" class="global-filter-item-search" @click="rePosts">搜索</el-button>
                    </li>
                    <li class="global-filter-item">
                        <el-button class="global-filter-item-search" @click="restart">重置</el-button>
                    </li>
                     <li class="global-filter-item">
                        <el-button type="success" class="global-filter-item-search" @click="addMsg">新增</el-button>
                    </li>
                </ul>
            </li>
        </ul> -->
        <div class="global-table-content">
            <div class="global-table-content-a">
                <el-table :data="dataList" style="width: 100%" :row-style="{ height: '0' }"
                    :cell-style="{ padding: '3px' }" max-height="620" border v-loading="tableLoading">
                    <el-table-column prop="id" label="编号" show-overflow-tooltip width="60px">
                    </el-table-column>
                    <el-table-column prop="fileName" label="文件名称" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="fileTypeName" label="文件类型" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="remark" label="备注" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="createPerson" label="创建人" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="createDate" label="创建时间" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="rejectReason" label="驳回理由" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="rejectPerson" label="处理人" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="rejectDate" label="重新配包时间" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="rejectStatusValue" label="重新配包状态" show-overflow-tooltip>
                    </el-table-column>
                    <el-table-column prop="finalType" label="终版状态" show-overflow-tooltip>
                        <template slot-scope="scope">
                            <div>
                                <el-tag type="danger" v-if="scope.row.finalType == 2">终版</el-tag>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" label="操作" width="300px">
                        <template slot-scope="scope">
                            <div style="display: flex;">
                                <FileDownloader :fileUrl="scope.row.filePath" :fileName="scope.row.fileName" />
                                <!-- <el-button v-if="operationList.includes('reject') && scope.row.rejectStatus == 1"
                                    style="font-size: 14px;" type="text"
                                    @click="handleReject(scope.row)">重新配包</el-button> -->
                                <el-button
                                    v-if="operationList.includes('project:surePackage')"
                                    style="font-size: 14px;" type="text"
                                    @click="handleSureFinal(scope.row)">确认终版</el-button>
                                <el-button
                                    v-if="operationList.includes('channelFinal') && scope.row.finalType == 2 && (scope.row.fileType == 5089 || scope.row.fileType == 5123)"
                                    style="font-size: 14px;" type="text"
                                    @click="handleChannelFinal(scope.row)">取消终版</el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
                <div class="global-page">
                    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                        :page-sizes="pageSizes" :page-size="pageSize" :current-page="pageNum" background
                        layout="sizes, total, prev, pager, next" :total="total">
                    </el-pagination>
                </div>
            </div>
          
            <div style="margin-top: 20px;display: flex;justify-content: center;" v-if="operationList.includes('project:rejectPackage')">
                <el-button type="primary" @click="handleReject">重新配包</el-button>
            </div>
        </div>

        <!-- 新增编辑 -->
        <el-dialog :title="formTitle" :visible.sync="addMsgDialogVisible" width="50%" :before-close="addMsgHandleClose">
            <div>
                <el-form :model="addMsgForm" :rules="addMsgRules" ref="addMsgForm">
                    <el-form-item label="文件类型" prop="fileType" :label-width="formLabelWidth">
                        <el-select v-model="addMsgForm.fileType" filterable>
                            <el-option v-for="(item, index) in fileTypeList" :key="index" :label="item.sysValueName"
                                :value="item.id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="文件" prop="file" :label-width="formLabelWidth">
                        <el-upload class="upload-demo" ref="upload" drag action="#" :auto-upload="false" :limit="1"
                            :on-change="handleFileChange" :file-list="fileList">
                            <i class="el-icon-upload"></i>
                            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                            <!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div> -->
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="备注" prop="remark" :label-width="formLabelWidth">
                        <el-input v-model="addMsgForm.remark" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addMsgDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addMsgSubmit">确 定</el-button>
            </span>
        </el-dialog>


        <el-dialog title="驳回" :visible.sync="rejectDialogVisible" width="50%" :before-close="rejectHandleClose">
            <div>
                <el-form :model="rejectMsgForm" :rules="rejectMsgFormRules" ref="rejectMsgForm">
                    <el-form-item label="驳回理由" prop="rejectReason" :label-width="formLabelWidth">
                        <el-input v-model="rejectMsgForm.rejectReason" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="rejectDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitReject">确 定</el-button>
            </span>
        </el-dialog>

            <!-- 确认终版信息 -->
    <el-dialog
    title="确认终版信息"
    :visible.sync="confirmFinalVisible"
    width="50%"
    :before-close="handleConfirmClose"
  >
    <el-form
      :model="confirmFormData"
      :rules="confirmRules"
      ref="confirmForm"
      label-width="130px"
    >
      <!-- <el-form-item label="确认时间" prop="confirmTime">
        <el-date-picker
          v-model="confirmFormData.confirmTime"
          type="datetime"
          placeholder="选择确认时间"
          format="yyyy-MM-dd HH:mm:ss"
          valueFormat="yyyy-MM-dd HH:mm:ss"
          clearable
          editable
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="开票公司">
        <el-select v-model="confirmFormData.invoiceCompany" placeholder="请选择开票公司">
          <el-option v-for="(item) in fileTypeList2" :key="item.id"  :label="item.sysValueName" :value="item.id"></el-option>
        </el-select>
        </el-form-item>

        <el-form-item label="开票金额">
          <el-input-number v-model="confirmFormData.invoicePrice" :precision="2" @change="handleChange"></el-input-number>
          </el-form-item> -->

          <el-form-item label="预估自营媒体成本">
            <el-input-number :precision="2" v-model="confirmFormData.estimatedSelfMediaCost" ></el-input-number>
            </el-form-item>

            <el-form-item label="预估外采媒体成本">
              <el-input-number :precision="2" v-model="confirmFormData.estimatedExternalMediaCost" ></el-input-number>
              </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="confirmFinalVisible = false">取消</el-button>
      <el-button type="primary" @click="submitConfirmFinal">确定</el-button>
    </span>
  </el-dialog>

    </div>
</template>

<script>
import APIProjectFile from "@/api/apiProjectFile";
import APISysLabel from "@/api/apiSysLabel";
import APIdetail from "@/api/apidetail";
import FileDownloader from "@/components/utils/FileDownloader";
export default {
    name: "ConpackageProject",
    components: {
        FileDownloader
    },
    props: {
        operationList: Array,
        isShow: Boolean,
        currentStageid:Number
    },
    data() {
        return {
            confirmFinalVisible: false, 
            fileId:null,
            confirmRules: {
        // 确认时间验证规则
        confirmTime: [
          { required: true, message: "请选择确认时间", trigger: "change" },
        ],
      },
      confirmFormData: {
        // confirmTime: new Date(), 
        // invoiceCompany:'',
        // invoicePrice:'',
        // orderNo:'',
        // productName:''
        estimatedExternalMediaCost:'',
        estimatedSelfMediaCost:''
      },
      fileTypeList2:[],
            // 表格相关
            tableLoading: true,
            dataList: [],
            pageSize: 15,
            pageNum: 1,
            total: 0,
            pageSizes: [10, , 15, 20, 50],
            tokenData: {
                token: "",
            },
            searchForm: {
                keyword: "",
                fileType: null,
                rejectStatus: null,
                createDate: "",
                rejectDate: "",
            },
            userInfo: {},
            projectId: null,
            rejectStatusList: [
                {
                    label: "可用",
                    value: 1,
                },
                {
                    label: "已驳回",
                    value: 2,
                },
            ],
            formLabelWidth: "120px",
            formTitle: "新增",
            addMsgDialogVisible: false,
            addMsgForm: {
                id: null,
                projectId: null,
                fileType: null,
                remark: '',
                file: null,
                fileName: '',
            },
            addMsgRules: {
                fileType: { required: true, message: '请选择文件类型', trigger: 'change' },
                // file: { required: true, message: '请上传文件' },
            },
            fileTypeList: [],
            rejectMsgForm: {
                projectId: null,
                rejectReason: '',
            },
            rejectMsgFormRules: {
                rejectReason: { required: true, message: '请输入驳回理由', trigger: 'blur' },
            },
            rejectDialogVisible: false,
            fileList: [],
            pickerOptions: {
                shortcuts: [{
                    text: '最近一周',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近一个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                        picker.$emit('pick', [start, end]);
                    }
                }, {
                    text: '最近三个月',
                    onClick(picker) {
                        const end = new Date();
                        const start = new Date();
                        start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                        picker.$emit('pick', [start, end]);
                    }
                }]
            },
        };
    },
    created() {
       // let item = JSON.parse(localStorage.getItem("viewProject"))
      //  this.projectId = item.projectId
      let projectId = this.$ls.get("projectId");
      this.projectId = projectId
        this.tokenData.token = this.$store.state.token;
        this.userInfo = JSON.parse(localStorage.getItem("mujinguserInfo"))
        this.searchForm = {
            keyword: "",
            fileType: null,
            rejectStatus: null,
        }
        this.getSysLabelList()
        this.getPost()
    },
    methods: {
        handleClickChannelFinal(row) {
            const params = {
                id: row.id
            }
            params.token = this.$store.state.token
            APIProjectFile.channelFinalFile(params).then((res) => {
                if (res.key === 1000) {
                    this.$message({
                        message: '取消成功',
                        type: 'success'
                    });
                    this.getPost()
                    this.$emit('get-stage')
                }
            });
        },
        handleChannelFinal(row) {
            this.$confirm('此操作将取消该终版文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.handleClickChannelFinal(row)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        handleSureFinal(row) {
      if (row.id) {
        this.fileId = row.id;
      }
      this.confirmFinalVisible = true;
    },
        handleClickSureFinal(row){
            const params = {
                id: row.id
            }
            params.token = this.$store.state.token
            APIProjectFile.sureFinalFile(params).then((res) => {
                if (res.key === 1000) {
                    this.$message({
                        message: '确认成功',
                        type: 'success'
                    });
                    this.getPost()
                    this.$emit('get-stage')
                }
            });
        },
          // 关闭弹窗时重置表单
    handleConfirmClose() {
      this.$refs.confirmForm.resetFields();
      this.confirmFinalVisible = false;
    },
    handleChange(){

},
  // 提交确认终版
  submitConfirmFinal() {
      this.$refs.confirmForm.validate((valid) => {
        if (valid) {
          const params = {
            //chooseDate: new Date(this.confirmFormData.confirmTime).getTime(),
            projectId: this.projectId,
            token: this.$store.state.token,
            fileId:this.fileId,
            estimatedExternalMediaCost:this.confirmFormData.estimatedExternalMediaCost,
            estimatedSelfMediaCost:this.confirmFormData.estimatedSelfMediaCost
            // invoiceCompany:this.confirmFormData.invoiceCompany,
            // invoicePrice:this.confirmFormData.invoicePrice,
            // orderNo:this.confirmFormData.orderNo,
            // productName:this.confirmFormData.productName,
          };
          APIdetail.doSurePackage(params).then((res) => {
            if (res.key === 1000) {
              this.$message.success("确认成功");
             // this.getPost();
              this.$emit("get-stage");
              this.confirmFinalVisible = false; // 关闭弹窗
            }
          });
        }
      });
    },
        // handleSureFinal(row) {
        //     this.$confirm('此操作将确认该文件为终版, 是否继续?', '提示', {
        //         confirmButtonText: '确定',
        //         cancelButtonText: '取消',
        //         type: 'warning'
        //     }).then(() => {
        //         this.handleClickSureFinal(row)
        //     }).catch(() => {
        //         this.$message({
        //             type: 'info',
        //             message: '已取消'
        //         });
        //     });
        // },
        submitReject(){
            this.$refs["rejectMsgForm"].validate((valid) => {
                if (valid) {
                    const params = this.rejectMsgForm
                    params.token = this.$store.state.token
                    APIdetail.rePackage(params).then((res) => {
                        if (res.key === 1000) {
                            this.$message({
                                message: '驳回成功',
                                type: 'success'
                            });
                            this.getPost();
                            this.rejectDialogVisible = false;
                            this.$emit('get-stage');
                        }
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        rejectHandleClose(){
            this.rejectDialogVisible = false
        },
        handleDownload(row){
            console.log("row", row)
            // 1. 已知的文件URL（示例：可替换为后端返回的文件地址）
            const fileUrl = row.filePath;
            // 2. 自定义下载后的文件名（可选，不填则用URL中的原始文件名）
            const fileName = row.fileName;
            // 3. 动态创建<a>标签
            const link = document.createElement("a");
            // 4. 设置文件URL（若为跨域URL，需后端配合设置响应头，否则download属性可能失效）
            link.href = fileUrl;
            // 5. 关键：添加download属性，强制触发下载（值为自定义文件名）
            link.download = fileName;
            // 6. 隐藏标签（不影响页面）
            link.style.display = "none";
            // 7. 添加到DOM中（部分浏览器需挂载后才能触发点击）
            document.body.appendChild(link);
            // 8. 模拟点击触发下载
            link.click();
            // 9. 下载后移除标签，清理DOM
            setTimeout(() => {
                document.body.removeChild(link);
            }, 100);
        },
        handleFileChange(file, fileList) {
            // file: 当前操作的文件对象
            // fileList: 所有已选择的文件列表
            console.log(file, fileList)
            this.fileList = fileList
            this.addMsgForm.file = file.raw
            this.addMsgForm.fileName = file.name
        },
        formatterRejectStatus(row) {
            return row.status == 1 ? '可用' : row.status == 2 ? '已驳回' : '未知'
        },
        handleReject(row) {
            this.rejectMsgForm = {
                projectId:this.projectId,
                rejectReason: '',
            }
            this.rejectDialogVisible = true
        },
        addMsgSubmit() {
            this.$refs["addMsgForm"].validate((valid) => {
                if (valid) {
                    const params = this.addMsgForm
                    params.projectId = this.projectId
                    params.token = this.$store.state.token
                    APIProjectFile.doAddProjectFile(params).then((res) => {
                        if (res.status === 200 && (!res.data.key || res.data.key === 1000)) {
                            this.$message({
                                message: '添加成功',
                                type: 'success'
                            });
                            this.fileList = []
                            this.$refs.upload.clearFiles();
                            this.getPost()
                            this.addMsgDialogVisible = false
                        }
                    });
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        addMsg() {
            this.addMsgForm = {
                id: null,
                projectId: null,
                fileType: null,
                remark: '',
                file: null,
                fileName: '',
            }
            this.addMsgDialogVisible = true
        },
        addMsgHandleClose() {
            this.addMsgDialogVisible = false
        },
        formatterTime(time) {
            return this.$moment(time).format("YYYY-MM-DD HH:mm:ss");
        },
        formatterDate(time) {
            return this.$moment(time).format("YYYY-MM-DD");
        },
        // 重置
        restart() {
            // 搜索条件重置
            this.searchForm = {
                keyword: "",
                fileType: null,
                rejectStatus: null,
                createDate: "",
                rejectDate: "",
            };
            this.rePosts();
        },
        // 分页pageSize改变
        handleSizeChange(e) {
            this.pageSize = e;
            this.rePosts();
        },
        // 分页pageNum改变
        handleCurrentChange(e) {
            this.pageNum = e;
            this.getPost();
        },
        // 重新请求
        rePosts() {
            this.pageNum = 1;
            this.dataList = [];
            this.getPost();
        },
        // 表格列表
        getPost() {
            this.tableLoading = true;
            const params = {
                token: this.$store.state.token,
                pageNum: this.pageNum,
                pageSize: this.pageSize,
                projectId: this.projectId,
                fileType:5123,
                stageId: this.currentStageid,
            };
            if (this.searchForm.keyword) {
                params.keyword = this.searchForm.keyword
            }
            if (this.searchForm.fileType) {
                params.fileType = this.searchForm.fileType
            }
            if (this.searchForm.rejectStatus) {
                params.rejectStatus = this.searchForm.rejectStatus
            }
            if (this.searchForm.createDate) {
                params.createStartTime = new Date(this.searchForm.createDate[0]).getTime()
                params.createEndTime = new Date(this.searchForm.createDate[1]).getTime()
            }
            if (this.searchForm.rejectDate) {
                params.rejectStartTime = new Date(this.searchForm.rejectDate[0]).getTime()
                params.rejectEndTime = new Date(this.searchForm.rejectDate[1]).getTime()
            }
            APIProjectFile.getProjectFileList(params).then((res) => {
                if (res.key === 1000) {
                    res = res.result;
                    this.total = res.count;
                    res.list.forEach(item => {
                        if (item.createTime) {
                            item.createDate = this.formatterTime(item.createTime)
                        }
                        if (item.rejectTime) {
                            item.rejectDate = this.formatterTime(item.rejectTime)
                        }
                        if (item.rejectStatus) {
                            item.rejectStatusValue = item.rejectStatus == 1 ? '可用' :
                                item.rejectStatus == 2 ? "已驳回" : "未知"
                        }
                    })
                    this.dataList = res.list;
                    this.tableLoading = false;
                }
            });
        },
        getSysLabelList() {
            const params = {
                token: this.$store.state.token,
                sysLabelIds: "51,18",
            };
            APISysLabel.getSysLabelValueManageList(params).then((res) => {
                if (res.key === 1000) {
                    this.fileTypeList = res.result.data[51]
                    this.fileTypeList2 = res.result.data[18]
                }
            });
        },

    },
};
</script>

<style lang="sass">
</style>

